package com.diyunapp.xilinapp.selfdefine;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.RadioGroup;

/**
 * Created by NIDAYE on 2016/7/25.
 */
public class FlowRadioGroup extends RadioGroup {

    private final static int VIEW_MARGIN_WIDTH=20;
    private final static int VIEW_MARGIN_HEIGHT=15;

    public FlowRadioGroup(Context context) {
        super(context);
    }

    public FlowRadioGroup(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int stages = 1;
        int stageHeight = 0;
        int stageWidth = 0;

        int wholeWidth = MeasureSpec.getSize(widthMeasureSpec);
        for (int i = 0; i < getChildCount(); i++) {
            final View child = getChildAt(i);
            // measure
            measureChild(child, widthMeasureSpec, heightMeasureSpec);
            stageWidth += (child.getMeasuredWidth() + VIEW_MARGIN_WIDTH);
            stageHeight = child.getMeasuredHeight();

            if (stageWidth >= wholeWidth) {
                stages++;
                //reset stageWidth
                stageWidth = child.getMeasuredWidth();
            }
        }

        Log.i("zhangxiaoxidebug","stageHeight="+stageHeight);
        int wholeHeight = (stageHeight + VIEW_MARGIN_HEIGHT) * stages;
        Log.i("zhangxiaoxidebug","wholeHeight="+wholeHeight);

        // report this final dimension
        setMeasuredDimension(resolveSize(wholeWidth, widthMeasureSpec),
                resolveSize(wholeHeight, heightMeasureSpec));
    }

    @Override
    protected void onLayout(boolean arg0, int arg1, int arg2, int arg3, int arg4) {
        Log.i("zhangxiaoxidebug","arg0="+arg0);
        Log.i("zhangxiaoxidebug","arg1="+arg1);
        Log.i("zhangxiaoxidebug","arg2="+arg2);
        Log.i("zhangxiaoxidebug","arg3="+arg3);
        Log.i("zhangxiaoxidebug","arg4="+arg4);

        final int count = getChildCount();
        int row=0;// which row lay you view relative to parent
        int lengthX=arg1 ;    // right position of child relative to parent
        int lengthY=0;    // bottom position of child relative to parent

        for(int i=0;i<count;i++) {
            final View child = this.getChildAt(i);
            int width = child.getMeasuredWidth();
            int height = child.getMeasuredHeight();

            if(i==0)
            {
                lengthX = width + arg1;//设置子控件的右下角X坐标
            }
            else
            {
                lengthX += (width + VIEW_MARGIN_WIDTH);//设置子控件的右下角X坐标
            }

            if (lengthX > arg3) {
                lengthX = width + arg1;
                row++;
            }

            lengthY = row * (height + VIEW_MARGIN_HEIGHT) + height;
            child.layout(lengthX - width, lengthY - height, lengthX, lengthY);
        }
    }
}
